import babelpolyfill from 'babel-polyfill'
import axios from 'axios'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'

// 图片浏览插件
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
Vue.use(Viewer)
Viewer.setDefaults({
    Options: { 'inline': true, 'button': true, 'navbar': true, 'title': true, 'toolbar': true, 'tooltip': false, 'movable': true, 'zoomable': false, 'rotatable': true, 'scalable': true, 'transition': true, 'fullscreen': true, 'keyboard': true, 'url': 'data-source' }
})

// 加载进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import routes from './routes'
import globalVar from './api/var'

// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

Vue.prototype.GLOBAL = globalVar;
Vue.prototype.hosts = 'http://39.109.117.98:19527';
Vue.prototype.hosts_static = 'http://39.109.117.98:19527';


// 对比插件
import VueCodeMirror from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
Vue.use(VueCodeMirror);


// ueditor  npm install vue-quill-editor --save
import  VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
Vue.use(VueQuillEditor)


Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)


Vue.prototype.in_array = function(search,array){
  for(var i in array){
    if(array[i]==search){
      return true;
    }
  }
  return false;
}
//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
    routes
})

// 路由权限控制
router.beforeEach((to, from, next) => {
    if (to.path == '/reg') {
        next()
    } else {
        if (to.path == '/login') {
            // sessionStorage.removeItem('user');
            localStorage.removeItem('user');
            console.log('去登录')
            next()

        }else if(to.path == '/'){
            let user = localStorage.getItem('user');
            console.log(user);
            if(user){
                next({path: '/topUp'})
            }else{
                console.log('登录已过期，跳去登录页')
                next({path: '/login'})
            }

        }else{

            // let user = JSON.parse(sessionStorage.getItem('user'));
            let user = localStorage.getItem('user');
            if (!user && to.path != '/login') {
                next({path: '/login'})

            } else {
                if(user){
                    let role_uri = [],url = [],ok = false;
                    let j=0;
                    // router.options.routes.forEach(item=>{
                    //     if(item.role == user.role_type){
                    //         role_uri[j] = item.children;
                    //     }
                    //     j++;
                    // });

                    // role_uri.forEach(item=>{
                    //     item.forEach(uri=>{
                    //         url.push(uri.path)
                    //     });
                    // });
                    //
                    // for(let i in url){
                    //     if(url[i] == to.path){
                    //         ok = true;
                    //     }
                    // }
                    // if(!ok){
                    //     console.log('非法访问');
                    //     return false;
                    // }else{
                        next()
                    // }
                }
                next()


            }
        }

    }

})


const pending = {}
const CancelToken = axios.CancelToken
const removePending = (key, isRequest = false) => {
    if (pending[key] && isRequest) {
        pending[key]('取消重复请求')
    }
    delete pending[key]
}
const getRequestIdentify = (config, isReuest = false) => {
    let url = config.url
    if (isReuest) {
        url = config.baseURL + config.url.substring(1, config.url.length)
    }
    return config.method === 'get' ? encodeURIComponent(url + JSON.stringify(config.params)) : encodeURIComponent(config.url + JSON.stringify(config.data))
}
// ajax请求统一增加请求头
axios.interceptors.request.use(config => {
    var user = localStorage.getItem('user');
    if (user) {
        config.headers.common = {
            'Authorization': user,
        }
    }

    // 拦截重复请求(即当前正在进行的相同请求)
    let requestData = getRequestIdentify(config, true)
    removePending(requestData, true)

    config.cancelToken = new CancelToken((c) => {
        pending[requestData] = c
    })

    return config
}, error => {
    if(error && err.response){
        console.log(12313)
    }
    return Promise.reject(error)
})


// 响应统一处理
axios.interceptors.response.use(function (response) {

    // 用户信息是否超时，重定向到登录页面
    if (response.data.Code == 401){
        ElementUI.Message({
            message: '授权已过期,请重新登录',
            type: 'warning'
        });
        setTimeout(function () {
            // sessionStorage.removeItem('user');
            localStorage.removeItem('user');
            router.replace({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}
            })
        },1500)
    }
    return response
}, function (error) {

    return Promise.reject(error)
})

new Vue({
    //el: '#app',
    //template: '<App/>',
    router,
    store,
    //components: { App }
    render: h => h(App)
}).$mount('#app')


